<template>
  <el-tabs v-model="currentTab" type="border-card" class="j-tabs" @tab-change="onTabChange">
    <el-tab-pane name="1" label="动态住宅">
      <div class="proxy-form mt-0">
        <div class="form-main">
          <div class="title"><span>生成代理</span>（同时支持HTTP/HTTPS SOCKS5协议）</div>
          <div class="form">
            <el-form label-width="120px" :model="proxyForm" ref="proxyFormRef" :rules="rules" size="large">
              <el-form-item label="国家/地区" prop="country">
                <el-select
                  v-model="proxyForm.country"
                  filterable
                  clearable
                  placeholder="请选择国家和地区"
                  class="full-width"
                  @change="onCountryChange"
                >
                  <el-option v-for="item in countryList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="州" prop="region">
                <el-select
                  v-model="proxyForm.region"
                  filterable
                  clearable
                  placeholder="请选择州/省"
                  class="full-width"
                  @change="onRegionChange"
                >
                  <el-option v-for="item in regionList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="市" prop="city">
                <el-select v-model="proxyForm.city" filterable clearable placeholder="请选择城市" class="full-width" @change="onCityChange">
                  <el-option v-for="item in cityList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="接入点" prop="node">
                <el-select v-model="proxyForm.node" placeholder="请选择接入点" class="full-width">
                  <template v-for="(item, index) in pointsList" :key="item.label + '-' + index">
                    <el-option v-if="item.label == proxyForm.country" :label="item.value" :value="item.value" />
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="IP时长" prop="time">
                <el-select v-model="proxyForm.time" placeholder="请选择有效时长（分钟）" class="full-width">
                  <el-option label="5" :value="5" />
                  <el-option label="10" :value="10" />
                  <el-option label="15" :value="15" />
                  <el-option label="30" :value="30" />
                  <el-option label="45" :value="45" />
                  <el-option label="60" :value="60" />
                  <el-option label="90" :value="90" />
                </el-select>
              </el-form-item>
              <el-form-item label="生成账号数量" prop="quantity">
                <el-input v-model.number="proxyForm.quantity" type="number" autocomplete="off" placeholder="请输入生成账号数量" />
              </el-form-item>
              <el-form-item label="代理密码" prop="password">
                <div class="pwd-item">
                  <el-input v-model="proxyForm.password" placeholder="首次生成代理必须设置密码" />
                  <!-- <el-button type="primary">修改密码</el-button> -->
                </div>
              </el-form-item>
              <el-form-item>
                <div style="white-space: nowrap">
                  <el-button
                    style="width: 134px"
                    class="primary-btn"
                    type="primary"
                    :disabled="loading"
                    :loading="loading"
                    @click="onSubmit(proxyFormRef)"
                    >提交</el-button
                  >
                  <el-button style="width: 134px" class="info-btn" type="primary" :disabled="loading" @click="onReset(proxyFormRef)">重置</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="form-tips">
          <el-scrollbar :always="true" height="540px">
            <p class="title">使用说明</p>
            <p class="info">所有用户自动生成账号，可指定国家、州省、城市。</p>
            <p class="info">设置IP使用时长（指网络连接开始至结束的时间，到时间结束只会切换IP不影响网络使用）。</p>
            <p class="info">代理密码由用户自己设置，从而提高安全性。</p>

            <p class="info mt-10">系统采购了AWS CDN服务，所有网络就近接入，目前提供三个代理服务器接入点：</p>
            <p class="info">gate1.ipxproxy.com(使用南美与北美国家ip请选择)</p>
            <p class="info">gate2.ipxproxy.com(使用亚太国家ip请选择)</p>
            <p class="info">gate3.ipxproxy.com(使用欧洲与非洲国家ip请选择)</p>
            <p class="info">所有代理服务端口： 7778</p>

            <p class="title">示例说明</p>
            <p class="info">例代理子账号：IPX_1000_US_001_0002_5_9978</p>
            <p class="info">PX_1000: 用户ID（固定不变）</p>
            <p class="info">US：国家代码（US美国）</p>
            <p class="info">001：US国家的一个州代码（具体查看国家地区州城市编码表）</p>
            <p class="info">0002：001这个洲下的一个城市编码（具体查看国家地区州城市编码表）</p>
            <p class="info">5：ip使用时长（单位：分钟，最低时长5分钟，最高90分钟，需大于等于5）</p>
            <p class="info"
              >1001: sessionID
              ,由英文与数字组成，长度1--32位，不同的sessionID代表不同的代理子帐号，通过修改sessionID,可以生成很多代理子帐号。</p
            >
            <p class="info mt-10">比如：IPX_1000_US_001_0002_5_1001，IPX_1001_US_001_0002_5_1002，就是二个代理子帐号</p>

            <p class="title">进阶说明</p>
            <p class="info">1、只需要定位到州，代理子账号这样组成：</p>
            <p class="info">IPX_1000_US_001__5_1001（代表获取美国001州一个时长为5分钟的ip）</p>
            <p class="info">IPX_1000_US_001__10_1001（代表获取美国001州一个时长为10分钟的ip）</p>
            <p class="info">注意：州代码与时长代码之间是两个‘_’</p>

            <p class="info mt-10">2、只需要定位到国家，代理子帐号这样组成：</p>
            <p class="info">IPX_1000_US___5_1001 （代表获取美国一个使用时长为5分钟的ip）</p>
            <p class="info">IPX_1000_US___10_1001 （代表获取美国一个使用时长为10分钟的ip）</p>
            <p class="info">注意：国家代码与时长代码之间是三个‘_’</p>

            <p class="info mt-10">同一代理子帐号在同一时间分配的代理IP相同，同一代理子帐号可以同时在不同设备上使用，但是ip都是同一个。</p>
          </el-scrollbar>
        </div>
      </div>
      <div class="mt-20">
        <el-table :data="data" border stripe style="width: 100%" class="j-table mt-0">
          <el-table-column prop="created_time" label="生成时间" />
          <el-table-column prop="country" label="国家/地区" />
          <el-table-column prop="region" label="洲/市" />
          <el-table-column prop="quantity" label="生成数量" />
          <el-table-column prop="action" label="操作" width="200px">
            <template #default="scope">
              <el-button @click="onDownload(scope.row)" type="primary" text :icon="Download">下载</el-button>
              <el-button @click="onDelete(scope.row)" type="primary" text :icon="Delete" style="margin-left: 0">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="j-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="page"
            :pageSize="limit"
            :total="total"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane name="2" label="使用记录">
      <Record ref="recordRef" @page-loading="onPgeLoading" />
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { regionApi, proxyCreateApi, proxyDownloadApi, proxyDeleteApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import { Download, Delete } from '@element-plus/icons-vue';
  import Record from './components/record.vue';

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const props = defineProps<{
    data: Array;
    limit: any;
    page: any;
    total: any;
  }>();

  const emits = defineEmits<{
    (event: 'confirm'): void;
    (event: 'page-change'): void;
    (event: 'page-loading'): void;
  }>();

  const recordRef = ref();
  const loading = ref(false);
  const currentTab = ref('1');
  const proxyFormRef = ref<FormInstance>();
  const proxyForm = reactive({
    country: '',
    region: '',
    city: '',
    node: '',
    time: '',
    quantity: '',
    password: '',
  });
  const rules = reactive<FormRules>({
    country: [{ required: true, message: '请选择国家和地区', trigger: 'change' }],
    region: [{ required: true, message: '请选择州/省', trigger: 'change' }],
    city: [{ required: true, message: '请选择区/县', trigger: 'change' }],
    node: [{ required: true, message: '请选择接入点', trigger: 'change' }],
    time: [{ required: true, message: '请选择有效时长', trigger: 'change' }],
    quantity: [{ required: true, type: 'number', message: '请填写生成账号数量', trigger: 'blur' }],
    password: [{ required: true, message: '请生成代理密码', trigger: 'blur' }],
  });

  const countryList = ref([]);
  const regionList = ref([]);
  const cityList = ref([]);
  const pointsList = ref([]);

  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onProxyCreate();
      }
    });
  };

  const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };

  const onProxyCreate = async () => {
    if (loading.value) return false;
    loading.value = true;
    proxyCreateApi(proxyForm)
      .then((res) => {
        loading.value = false;
        if (res.errcode == 0) {
          ElMessage.success(res.message || res.errmsg);
          onCurrentChange(1);
          proxyFormRef.value.resetFields();
          nextTick(() => {
            proxyFormRef.value.clearValidate();
          });
        } else {
          ElMessage.error(res.message || res.errmsg);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onDownload = (row) => {
    // if (loading.value) return false;
    loading.value = true;
    proxyDownloadApi({ batch_id: row.id })
      .then((res) => {
        loading.value = false;
        if (res.message || res.errmsg) {
          ElMessage.success(res.message || res.errmsg);
          return false;
        }
        let url = window.URL.createObjectURL(new Blob([res]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', `${new Date().getTime()}_proxy.text`);
        document.body.appendChild(link);
        link.click();
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onDelete = (row) => {
    ElMessageBox.confirm('是否删除？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        onDeleteFn(row);
      })
      .catch(() => {});
  };

  const onDeleteFn = async (row) => {
    // if (loading.value) return false;
    loading.value = true;
    proxyDeleteApi({ batch_id: row.id })
      .then((res) => {
        ElMessage.success(res.message || res.errmsg);
        loading.value = false;
        if (res.errcode == 0) {
          onCurrentChange(props.page);
        }
      })
      .catch((err) => {
        console.log('err', err);
        loading.value = false;
        ElMessage.error(err.message);
      });
  };

  const onTabChange = (val) => {
    if (val == '1') {
      emits('page-change', 1);
    } else if (val == '2') {
      recordRef.value.onPageChange('traffic', 1);
    }
  };

  const onCurrentChange = (val) => {
    emits('page-change', val);
  };

  const onCountryChange = (val) => {
    if (val) {
      getRegion('region', val);
    }
  };

  const onRegionChange = (val) => {
    if (val) {
      getRegion('city', val);
    }
  };

  const onCityChange = () => {};

  const getRegion = async (type, code = '') => {
    regionApi({
      type: type,
      code: code,
    })
      .then((res) => {
        if (res.data) {
          if (type == 'country') {
            countryList.value = res.data;
          }
          if (type == 'region') {
            regionList.value = res.data;
          }
          if (type == 'city') {
            cityList.value = res.data;
          }
          if (res.points) {
            pointsList.value = [];
            for (let i in res.points) {
              pointsList.value.push({
                label: i,
                value: res.points[i],
              });
            }
          }
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onPgeLoading = (val) => {
    emits('page-loading', val);
  };

  onMounted(() => {
    getRegion('country');
  });
</script>

<style scoped lang="scss"></style>
